package vn.lumi.smarthome.ui;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import vn.lumi.smarthome.ActivityHelper;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.DatabaseHelper;
import vn.lumi.smarthome.io.database.TBL_Device;
import vn.lumi.smarthome.io.database.TBL_Floor;
import vn.lumi.smarthome.io.database.TBL_Room;
import vn.lumi.smarthome.network.TurnOnScene;
import vn.lumi.smarthome.provider.SmartHomeProvider;
import vn.lumi.smarthome.service.ReceiveDataThread;
import vn.lumi.smarthome.service.SmartHomeService;
import vn.lumi.smarthome.service.TransmitThread;
import vn.lumi.smarthome.ui.MainFragment.OnTabSelectedListener;
import vn.lumi.smarthome.ui.MainFragment.TABS;

import vn.lumi.smarthome.ui.MenuFragment.OnFloorRoomClickListener;
import vn.lumi.smarthome.ulti.LogUltis;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TypefaceSpan;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class MainActivity extends SlidingFragmentActivity implements
		OnFloorRoomClickListener, OnTabSelectedListener, OnClickListener {
	private static final String TAG = "MainActivity";

	private static final int TAB_DEVICE = 0;
	private static final int TAB_SCENE = 1;
	int mCurrentTab = TAB_DEVICE;
	private static final String KEY_CURRENT_TAB = "key_current_tab";

	// private MenuItem mMenuItem_AddScene;
	// private MenuItem mMenuItem_ModifyScene;

	// Cac bien luu gia tri room_id vs floor_id dang duoc chon
	private int mRoomId = 0; // Mac dinh phong khong bao gio co mRoomID =0
	private int mFloorId;

	// Cac bien luu gia tri cua Room_id va Floor_id ma ben AddSceneActivity gui
	// cho
	private int returnRoomId;

	// Layout actionBar
	LinearLayout layoutActionbar;
	ImageButton acbar_home;
	Button btn_switch, btn_turnAllon, btn_turnAlloff, btn_addScene,
			btn_editScene;
	Boolean isDevice = true; // Kiểm tra trạng thái của button switch
	TextView titleActionbar;

	SlidingMenu slidingMenu;

	boolean isEditScene = true; // Luc dau true de co the bam edit
	boolean isEnterAdddScene = false; // Kiem tra xem luc dau nhay vao fragment
										// canh
	boolean isEnterEditScene = false;
	boolean isAnotherActivity = false;
	
	// hay thiet bi
	String nameRoom = null;
	String nameFloor = null;
	// Socket
	Socket socket = null;
	InputStream is;
	OutputStream os;

	public static final int ADD_SCENE_REQUEST = 1; 
	public static final int EDIT_SCENE_REQUEST = 2;
	public static final int SETTING_REQUEST = 3; 
	public static final int ANOTHER_REQUEST = 4; // Danh cho cac activity khac mac dinh vao device fragment
	public static final String STRING_ANOTHER_REQUEST = "another_request";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (savedInstanceState != null) {
			mCurrentTab = savedInstanceState.getInt(KEY_CURRENT_TAB);
		}

		Intent intent = getIntent();
		boolean finish = intent.getBooleanExtra("finish", false);
		if (finish) {
			Intent i = new Intent(MainActivity.this, LoginActivity.class);
			startActivity(i);
			finish();
			return;
		}

		setBehindContentView(R.layout.activity_main_behind);
		setContentView(R.layout.activity_main);

		ActivityHelper.initialize(this);
		slidingMenu = getSlidingMenu();
		setupSlidingMenu(slidingMenu);
		setupActionBar();
		setupMenu();
		// Bind Service to Content Provider
		Context mContext = getApplicationContext();
		mContext.getContentResolver().delete(
				SmartHomeProvider.BIND_SERVICE_URI, null, null);
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			if (requestCode == ADD_SCENE_REQUEST) {
				// Nhan du lieu neu co tu cac activity khac tra ve
				isEnterAdddScene = intent.getBooleanExtra("Scene", false);
				returnRoomId = intent.getIntExtra("RoomID", mRoomId);
			} else if (requestCode == EDIT_SCENE_REQUEST) {
				isEnterEditScene = true;
			} else if (requestCode == ANOTHER_REQUEST ) {
				isAnotherActivity = intent.getBooleanExtra(MainActivity.STRING_ANOTHER_REQUEST, false);;
				returnRoomId = intent.getIntExtra("RoomID", mRoomId);
			}
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MainFragment.isActivityPause = false;

		// Danh cho phan them canh
		if (isEnterAdddScene) {
			// O day phai set lai fragment do khi nhay vao AddSceneActivity thi
			// MainFragment se nhay vao ham OnPause => DeviceFragment va
			// SceneFragment bi mat
			RecreatMainFragment(isEnterAdddScene, returnRoomId);
			isEnterAdddScene = false; // Thiet lap la false để chỉ ra rằng chỉ
										// có khi từ addSceneActivity nhảy về
										// MainActivity thì mới được dùng các
										// hàm này
			// Đề phòng trường hợp ở EditFragment mở AddSceneActivity
			btn_editScene
					.setBackgroundResource(R.drawable.img_editscene_selector); // Khi
																				// tra
																				// ve
																				// luon
																				// luôn
																				// tra
																				// ve
			// trang
																				// thai
																				// SceneFragment
			isEditScene = true;
		} else if (isEnterEditScene) {
			isEditScene = false;
			isEnterEditScene = false;
			// De tranh nhay vao ham SetHomeScene
		} else if (isAnotherActivity) {
			isAnotherActivity = false;
			RecreatMainFragment(isAnotherActivity, returnRoomId);
		}
		else if(mRoomId == 0) {
			setHomeScreen(false);

		}
		else {
			RecreatMainFragment(false, mRoomId);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_CURRENT_TAB, mCurrentTab);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item);
	}

	private void setupSlidingMenu(SlidingMenu slideMenu) {
		SlidingMenu slidingMenu = slideMenu;
		slidingMenu.setBehindOffsetRes(R.dimen.sliding_behind_offset);
		slidingMenu.setShadowWidthRes(R.dimen.sliding_shadow_width);
		slidingMenu.setFadeDegree(1.0f);
	}

	// -----------------------------Actionbar------------------
	private void setupActionBar() {
		ActionBar actionbar = getSupportActionBar();
		actionbar.setCustomView(R.layout.activity_actionbar);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
				| ActionBar.DISPLAY_SHOW_HOME);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayShowTitleEnabled(false);
		layoutActionbar = (LinearLayout) actionbar.getCustomView();
		btn_switch = (Button) findViewById(R.id.layout_actionbar_switch);
		btn_switch.setOnClickListener(this);
		acbar_home = (ImageButton) findViewById(R.id.layout_actionbar_home);
		acbar_home.setOnClickListener(this);
		btn_turnAlloff = (Button) findViewById(R.id.layout_actionbar_turnoff);
		btn_turnAlloff.setOnClickListener(this);
		btn_turnAllon = (Button) findViewById(R.id.layout_actionbar_turnon);
		btn_turnAllon.setOnClickListener(this);
		btn_addScene = (Button) findViewById(R.id.layout_actionbar_addScence);
		btn_addScene.setOnClickListener(this);
		btn_editScene = (Button) findViewById(R.id.layout_actionbar_editScence);
		btn_editScene.setOnClickListener(this);
		titleActionbar = (TextView) findViewById(R.id.layout_actionbar_title);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.layout_actionbar_home:
			if (isEditScene) {
				getSlidingMenu().showMenu(true);
			}
			break;
		case R.id.layout_actionbar_switch:
			if (isEditScene) {
				if (isDevice) {
					setButtonToScence();
					isDevice = false;
					// Bao cho ben ViewPage biet de chuyen sang Fragment canh
					switchMainFragment(isDevice);

				} else {
					setButtonToDevice();
					isDevice = true;
					// Bao cho ben ViewPage biet de chuyen sang Fragment device
					switchMainFragment(isDevice);
				}
			}
			break;
		case R.id.layout_actionbar_turnoff:
			turnAllOffOnRoom(mRoomId);
			break;
		case R.id.layout_actionbar_turnon:
			turnAllOnOnRoom(mRoomId);
			break;
		case R.id.layout_actionbar_addScence:
			Intent intent = new Intent(this, AddSceneActivity.class);
			intent.putExtra(AddSceneActivity.EXTRA_FLOOR_ID, mFloorId);
			intent.putExtra(AddSceneActivity.EXTRA_ROOM_ID, mRoomId);
			startActivityForResult(intent, ADD_SCENE_REQUEST);
			break;
		case R.id.layout_actionbar_editScence:
			FragmentManager fragmentManager = getSupportFragmentManager();
			FragmentTransaction transaction = fragmentManager
					.beginTransaction();

			if (isEditScene) {

				EditSceneFragment editFragment = EditSceneFragment.newInstance(
						mFloorId, mRoomId);
				transaction.replace(R.id.activity_main_content, editFragment,
						"editScene").commit();
				isEditScene = false;
				btn_editScene.setBackgroundResource(R.drawable.img_ok);
				slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
			} else {
				setTitleActionbar(nameRoom + "-" + nameFloor);
				MainFragment mainFragment = MainFragment.newInstance(mFloorId,
						mRoomId, MainFragment.SCREEN_SCENE);
				transaction.replace(R.id.activity_main_content, mainFragment,
						"main").commit();
				btn_editScene
						.setBackgroundResource(R.drawable.img_editscene_selector);

				slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);

				isEditScene = true;

			}
			break;
		default:
			break;
		}
	}

	private void setButtonToScence() {

		btn_switch.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.img_switch_canh));
		btn_turnAlloff.setVisibility(View.GONE);
		btn_turnAllon.setVisibility(View.GONE);
		btn_addScene.setVisibility(View.VISIBLE);
		btn_editScene.setVisibility(View.VISIBLE);
	}

	private void setButtonToDevice() {
		btn_switch.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.img_switch_dev));
		btn_turnAlloff.setVisibility(View.VISIBLE);
		btn_turnAllon.setVisibility(View.VISIBLE);
		btn_addScene.setVisibility(View.GONE);
		btn_editScene.setVisibility(View.GONE);
	}

	// ------------------------------------------------------------------
	private void setupMenu() {
		MenuFragment menuFragment = new MenuFragment();
		getSupportFragmentManager()
				.beginTransaction()
				.replace(R.id.activity_main_behind_content, menuFragment,
						"menu").commit();

	}

	private void setHomeScreen(boolean isSceneFragment) {

		Cursor cursor = null;
//		String[] projectionDev = { TBL_Device.ROOM_ID };
//		cursor = getContentResolver().query(TBL_Device.CONTENT_URI_DEVICES,
//				projectionDev, null, null, null);
//		cursor.moveToFirst();
//		mRoomId = cursor.getInt(cursor.getColumnIndex(TBL_Device.ROOM_ID));
//		cursor = null;

		// Truy van de lay id cua Room va Floor va ten cua room
		String[] projectionRoom = new String[] { TBL_Room._ID, TBL_Room.FLOOR_ID,
				TBL_Room.NAME };
//		String selectionRoom = TBL_Room._ID + "=?";
//		String[] selectionArgsRoom = { mRoomId + "" };
		cursor = getContentResolver().query(TBL_Room.CONTENT_URI_ROOM,
				projectionRoom, null, null, TBL_Room._ID);
		cursor.moveToFirst();
		mRoomId = cursor.getInt(cursor.getColumnIndex(TBL_Room._ID));
		mFloorId = cursor.getInt(cursor.getColumnIndex(TBL_Room.FLOOR_ID));
		nameRoom = cursor.getString(cursor.getColumnIndex(TBL_Room.NAME));

		// Truy van de lay ten Floor
		cursor = null;
		String[] projection2 = { TBL_Floor.NAME };
		String selection = TBL_Floor._ID + "=?";
		String[] selectionArgs = { mFloorId + "" };
		cursor = getContentResolver().query(TBL_Floor.CONTENT_URI_FLOOR,
				projection2, selection, selectionArgs, null);
		cursor.moveToFirst();
		nameFloor = cursor.getString(cursor.getColumnIndex(TBL_Floor.NAME));
		cursor = null;

		setTitleActionbar(nameRoom + "-" + nameFloor);
		FragmentManager fragmentManager = getSupportFragmentManager();
		MainFragment fragment = (MainFragment) fragmentManager
				.findFragmentByTag("main");
		MainFragment mainFragment;
		if (fragment == null) {
			if (isSceneFragment) {
				mainFragment = MainFragment.newInstance(mFloorId, mRoomId,
						MainFragment.SCREEN_SCENE);
				setButtonToScence();
				isDevice = false;
			} else {
				mainFragment = MainFragment.newInstance(mFloorId, mRoomId,
						MainFragment.SCREEN_DEVICE);
				setButtonToDevice();
				isDevice = true;
			}
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.activity_main_content, mainFragment, "main")
					.commit();
		} else {
			fragment.onlyRefreshData(mFloorId, mRoomId);
			if (isSceneFragment)
				fragment.SwitchFrament(false);
			else
				fragment.SwitchFrament(true);
			

		}

	}

	/**
	 * @param isSceneFragment
	 *            : Chuyen sang SceneFragment neu gia tri nay bang true
	 * @param room_id
	 *            : id cua phong ma se hien thi ra o MainFragment
	 * 
	 *            Ham nay de tao lai MainFragment
	 */
	private void RecreatMainFragment(boolean isSceneFragment, int room_id) {
		Cursor cursor = null;
		mRoomId = room_id;
		// Truy van de lay id cua Room va Floor va ten cua room
		String[] projectionRoom = new String[] { TBL_Room.FLOOR_ID,
				TBL_Room.NAME };
		String selectionRoom = TBL_Room._ID + "=?";
		String[] selectionArgsRoom = { mRoomId + "" };
		cursor = getContentResolver().query(TBL_Room.CONTENT_URI_ROOM,
				projectionRoom, selectionRoom, selectionArgsRoom, null);
		cursor.moveToFirst();
		mFloorId = cursor.getInt(cursor.getColumnIndex(TBL_Room.FLOOR_ID));
		nameRoom = cursor.getString(cursor.getColumnIndex(TBL_Room.NAME));

		// Truy van de lay ten Floor
		cursor = null;
		String[] projection2 = { TBL_Floor.NAME };
		String selection = TBL_Floor._ID + "=?";
		String[] selectionArgs = { mFloorId + "" };
		cursor = getContentResolver().query(TBL_Floor.CONTENT_URI_FLOOR,
				projection2, selection, selectionArgs, null);
		cursor.moveToFirst();
		nameFloor = cursor.getString(cursor.getColumnIndex(TBL_Floor.NAME));
		cursor = null;

		setTitleActionbar(nameRoom + "-" + nameFloor);
		FragmentManager fragmentManager = getSupportFragmentManager();
		MainFragment fragment = (MainFragment) fragmentManager
				.findFragmentByTag("main");
		MainFragment mainFragment;
		if (fragment == null) {
			if (isSceneFragment) {
				mainFragment = MainFragment.newInstance(mFloorId, mRoomId,
						MainFragment.SCREEN_SCENE);
				setButtonToScence();
				isDevice = false;
			} else {
				mainFragment = MainFragment.newInstance(mFloorId, mRoomId,
						MainFragment.SCREEN_DEVICE);
				setButtonToDevice();
				isDevice = true;
			}
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.activity_main_content, mainFragment, "main")
					.commit();
		} else {
			fragment.onlyRefreshData(mFloorId, mRoomId);
			if (isSceneFragment)
				fragment.SwitchFrament(false);
			else
				fragment.SwitchFrament(true);
			

		}

	}

	@Override
	public void onFloorRoomClick(int floor_id, int room_id, String floor_name,
			String room_name) {
		LogUltis.i(TAG, "Floor id=[" + floor_id + " vs room_id=[" + room_id);
		mRoomId = room_id;
		mFloorId = floor_id;
		FragmentManager fragmentManager = getSupportFragmentManager();
		MainFragment fragment = (MainFragment) fragmentManager
				.findFragmentByTag("main");
		if (fragment == null) {
			MainFragment mainFragment = MainFragment.newInstance(floor_id,
					room_id, MainFragment.SCREEN_DEVICE);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.activity_main_content, mainFragment, "main")
					.commit();
		} else {
			fragment.refreshData(mFloorId, mRoomId);
		}
		getSlidingMenu().showContent(true);
		setTitleActionbar(room_name + "-" + floor_name);
	}

	private void switchMainFragment(boolean isFragmentDevice) {
		FragmentManager fragmentManager = getSupportFragmentManager();
		MainFragment fragment = (MainFragment) fragmentManager
				.findFragmentByTag("main");
		if (fragment == null) {
			MainFragment mainFragment = MainFragment.newInstance(mFloorId,
					mRoomId, MainFragment.SCREEN_DEVICE);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.activity_main_content, mainFragment, "main")
					.commit();
			mainFragment.SwitchFrament(isFragmentDevice);
		} else {
			fragment.SwitchFrament(isFragmentDevice);
		}
	}

	private void turnAllOffOnRoom(int room_id) {
		FragmentManager fragmentManager = getSupportFragmentManager();
		MainFragment fragment = (MainFragment) fragmentManager
				.findFragmentByTag("main");
		if (fragment != null) {
			fragment.turnAllOffOnroom(room_id);
		} else {
			Toast.makeText(getApplicationContext(), "Lỗi", Toast.LENGTH_SHORT)
					.show();
		}
	}

	private void turnAllOnOnRoom(int room_id) {
		FragmentManager fragmentManager = getSupportFragmentManager();
		MainFragment fragment = (MainFragment) fragmentManager
				.findFragmentByTag("main");
		if (fragment != null) {
			fragment.turnAllOnOnRoom(room_id);
		} else {
			Toast.makeText(getApplicationContext(), "Lỗi", Toast.LENGTH_SHORT)
					.show();
		}
	}

	private void setTitleActionbar(String string) {

		/*
		 * Typeface TF = Typeface.createFromAsset(getApplication().getAssets(),
		 * LumiHome.font); getSupportActionBar().setTitleTypeface(TF);
		 * getSupportActionBar().setTitle(string);
		 */
		titleActionbar.setText(string);

	}

	@Override
	public void onTabSelected(TABS tab) {
		if (tab == TABS.DEVICE) {
			mCurrentTab = TAB_DEVICE;
			setButtonToDevice();
		} else if (tab == TABS.SCENE) {
			mCurrentTab = TAB_SCENE;
			setButtonToScence();
		}
		// supportInvalidateOptionsMenu();

	}

	@Override
	protected void onPause() {
		MainFragment.isActivityPause = true;
		if (isFinishing() == true) {
			getApplicationContext().getContentResolver().update(
					SmartHomeProvider.END_APPLICATION_URI, null, null, null);
			boolean stopservice = stopService(new Intent(
					getApplicationContext(), SmartHomeService.class));
			Log.d("Main Activity", "stopservice=" + String.valueOf(stopservice));
			ReceiveDataThread.End();
			TransmitThread.End();
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {

		getApplicationContext().getContentResolver().update(
				SmartHomeProvider.END_APPLICATION_URI, null, null, null);
		stopService(new Intent(getApplicationContext(), SmartHomeService.class));

		ReceiveDataThread.End();
		TransmitThread.End();
		Log.e("Destroy", "Destroy");
		super.onDestroy();
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		showCustomDialog("Thông báo", "Bạn có chắc chắn muốn thoát khỏi ứng dụng");
		
	}
	public void showCustomDialog(String title, String message) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));

		ChangeFont changeFont = new ChangeFont(this);
		TextView tvTitle = new TextView(this);
		tvTitle = changeFont.changeFontTextView(tvTitle, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvTitle);
		ErrorDialog.setMessage(message);
		ErrorDialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		ErrorDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				finish();
				dialog.cancel();
			}
		});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		alertErrorDialog.getWindow().getAttributes();
		TextView tvMessage = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		tvMessage = changeFont.changeFontTextView(tvMessage, message,
				LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenLight));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getAssets(),
				LumiHome.fontBold));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
		
		Button btn2 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_POSITIVE);
		btn2.setTypeface(Typeface.createFromAsset(getAssets(),
				LumiHome.fontBold));
		btn2.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn2.setTextSize(LumiHome.sizeButton);
	}

}
